package com.isoftstone.spring.subject.restful01;
import lombok.*;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.bind.annotation.*;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicLong;

/**
 * @Description: UserController
 */
@RestController
@RequestMapping("/user")
public class UserController {
    //生成user对象CRUD标准的Restful接口

    // 模拟数据库存储
    private static final ConcurrentHashMap<Long, User> userDatabase = new ConcurrentHashMap<>();
    private static final AtomicLong idGenerator = new AtomicLong(1);

    // 初始化一些测试数据
    static {
        userDatabase.put(1L, new User(1L, "张三", "zhangsan@example.com", 25));
        userDatabase.put(2L, new User(2L, "李四", "lisi@example.com", 30));
        idGenerator.set(3);
    }

    /**
     * 创建用户
     * POST /user
     */
    @PostMapping
    public User createUser(@RequestBody User user) {
        Long id = idGenerator.getAndIncrement();
        user.setId(id);
        userDatabase.put(id, user);
        return user;
    }

    /**
     * 获取所有用户
     * GET /user
     */
    @GetMapping
    public List<User> getAllUsers() {
        return new ArrayList<>(userDatabase.values());
    }

    /**
     * 根据ID获取用户
     * GET /user/{id}
     */
    @GetMapping("/{id}")
    public User getUserById(@PathVariable Long id) {
        return userDatabase.get(id);
    }

    /**
     * 更新用户信息
     * PUT /user/{id}
     */
    @PutMapping("/{id}")
    public User updateUser(@PathVariable Long id, @RequestBody User user) {
        user.setId(id);
        userDatabase.put(id, user);
        return user;
    }

    /**
     * 删除用户
     * DELETE /user/{id}
     */
    @DeleteMapping("/{id}")
    public void deleteUser(@PathVariable Long id) {
        userDatabase.remove(id);
    }

    // User实体类
    @Data
    @AllArgsConstructor
    @NoArgsConstructor
    public static class User {
        private Long id;
        private String name;
        private String email;
        private Integer age;
    }
}
